package com.oceansoft.mobile.biz.front.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.front.entity.AnswerUser;
import com.oceansoft.mobile.biz.front.entity.PrizeWinner;
import com.oceansoft.mobile.biz.front.entity.Question;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.common.util.Result;

@Service
public class QuestionServiceImpl implements IQuestionService{
	@Resource
	private ICommonDao commonDao;
	
	/**
	 * 获取所有问题列表
	 * @return
	 */
	@Override
	public Result getQuestionList() {
//		initData();
//		return null;
		try {
			List<Question> queslist = getFiveQuesList();
			if(!CollectionUtils.isEmpty(queslist)){
				for(Question question:queslist){
					question.setAnswerRight("");//将正确答案清空
				}
			}
			return new Result(Result.SUCC, (Object)queslist);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(Result.FAILURE, "数据加载失败");
		}
	}

	/**
	 * 提交问题答案
	 * 请求参数JSON格式：[{"answer":"A","questionId":"1"},{"answer":"B","questionId":"2"}]
	 * @return
	 */
	@Override
	public Result submitAnswer(String answer) {
		try {
			//if((Boolean)isJoin().getData())
				//return new Result(Result.FAILURE, "您已参加过此活动，很遗憾，您没中奖");
			
			JSONArray error = new JSONArray();//用于存放答错的问题
			JSONArray array = JSON.parseArray(answer);
			for(Question ques:getQuesList()){
				for(int i=0;i<array.size();i++){
					JSONObject obj = array.getJSONObject(i);
					if(ques.getId()==obj.getInteger("questionId")){
						AnswerUser answerUser = new AnswerUser();
						answerUser.setQuestId(ques.getId());
						answerUser.setOpenId(getOpenId());
						answerUser.setAnswer(obj.getString("answer"));
						answerUser.setScore(ques.getScore());
						
						if(!ques.getAnswerRight().toUpperCase().equals(obj.getString("answer").toUpperCase())){
							JSONObject object = new JSONObject();
							object.put("question", ques.getQuestion());
							object.put("answerRight", ques.getAnswerRight());
							object.put("answer", (ques.getAnswerOption().split("\\|\\|"))[2]);
							error.add(object);
							answerUser.setScore(0);
						}
						//将用户答案存入数据库
						//commonDao.saveOne("INSERT INTO sc_answer_user(quest_id,open_id,answer,score) VALUES(:questId,:openId,:answer,:score)", answerUser);
					}
				}
			}
			return new Result(Result.SUCC, error, "回答提交处理成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(Result.FAILURE, "回答提交处理失败");
		}
	}
	
	/**
	 * 是否参加过此活动
	 * false未参加	true已参加
	 * @return
	 */
	@Override
	public Result isJoin(String openId){
		//int _num = commonDao.getCount("SELECT COUNT(*) FROM t_winner T WHERE T.WEIXINID = ?", openId);
		//return new Result(Result.SUCC,_num>0?true:false);
		String sql = "select * from t_winner where weixinid='"+openId+"'";
		System.out.println("sql============================"+sql);
		List<PrizeWinner> list = commonDao.loadList(sql,PrizeWinner.getMap());
		System.out.println("list size============================"+list.size());
		return new Result(Result.SUCC,list,"数据加载成功");
	}
	
	/**
	 * 获取所有列表
	 */
	private List<Question> getQuesList() throws Exception{
		String sql = "select * from sc_question";
		return commonDao.loadList(sql,Question.getMap());
	}
	
	/**
	 * 初始化抽奖队列数据
	 */
	private void initData(){
		int prize[] = {50,100,200,600,1000};
		int rate[] = {4,8,10,26,58};
		Random random = new Random();
		
		for(;;){
			int pp = random.nextInt(99)+1;//1 - 100	中奖数
			
			//中奖率
			int _random = 0;
			int flag = 0;
			for(int k=0;k<rate.length;k++){
				_random += rate[k];
				if(pp<_random){
					flag = k;
					break;
				}
			}
			
			if(prize[flag]==0)
				continue;
			
			commonDao.update("insert into wx_price(award_type,status) values ("+flag+",0)");
			
			prize[flag]--;

			//奖项分配完毕时 程序终止
			int sum = 0;
			for (int i = 0; i < prize.length; i++) 
				sum += prize[i];
			
			if(sum==0)
				break;
		}
	}
	
	/**
	 * 获取所有列表 随机5条
	 * @return
	 * @throws Exception
	 */
	private List<Question> getFiveQuesList() throws Exception{
		String sql = "select * from sc_question";
		List<Question> list = commonDao.loadList(sql,Question.getMap());
		if(CollectionUtils.isEmpty(list)||list.size()<5) 
			return list;
		
		//List装题
		List<Question> rlist = new ArrayList<Question>();
		
		//产生0-19的5个随机数
		int[] ram = new int[5];
		Random random = new Random();
		for (int i = 0; i < ram.length; i++) {
			ram[i] = random.nextInt(20);
			
			for (int j = 0; j < i; j++) 
				if(ram[i] == ram[j])
					i--;
			
		}

		for (int i = 0; i < ram.length; i++) 
			rlist.add(list.get(ram[i]));
		
		return rlist;
	}
	
	/**
	 * 获取用户OPENID
	 * @return
	 */
	private String getOpenId(){
		return "ofYYxt_CJ5vjcjJSPrL4-V52OjTI";
	}

	@Override
	public void addPrizeQueue() {
		int a[] = new int[50];
		int b[] = new int[100];
		int c[] = new int[200];
		int d[] = new int[600];
		int e[] = new int[1000];
		
		
		
		
		
		//commonDao.update("insert into wx_joiner values(null,?,sysdate())",wxId);
	}
}







